import React, { useState } from 'react';
import { SyncOutlined, UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { Button, Upload, message } from 'antd';
import * as XLSX from 'xlsx';
import { post } from '@/useHttp';
import { ProColumns } from '@ant-design/pro-components';

type propTypes<T = any> = {
  url: string
  columns: ProColumns<T>[];
  onSuccess: () => void;
}

const readExcelFile = (file: any, props: propTypes) => {
  const reader = new FileReader();
  reader.onload = async (e: any) => {
    const data = e.target.result;
    const workbook = XLSX.read(data, { type: 'array', cellDates: true });

    // 假设我们总是处理第一个工作表  
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    // 修改标题与数据库一致(假设字段数 < 100)
    for (let index = 0; index < 100; index++) {
      const cell = String.fromCharCode(65 + index) + '1';
      if (!worksheet[cell]) break;
      const key = props.columns.find(item => item.title === worksheet[cell].v)?.dataIndex
      if (key) {
        worksheet[cell].v = key;
        worksheet[cell].h = key;
        worksheet[cell].w = key;
      }
    }
    // 将工作表数据转换为JSON  
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 0 }); // 假设第一行是标题行      
    const urls = props.url.split('/')
    urls.splice(2, 0, 'imp')
    const url = urls.join('/') // 修改url为导入接口
    const { success } = await post(url, jsonData)
    if (success) {
      message.success('导入成功')
      props.onSuccess()
    }
  };
  reader.readAsArrayBuffer(file);
};

const Import = (props: propTypes) => {
  const [loading, setLoading] = useState(false);
  // const token = localStorage.getItem('token')

  const upProps: UploadProps = {
    name: 'file',
    // action: 'https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload',
    // headers: {
    //   authorization: token ?? '',
    // },
    // withCredentials: true, // 允许携带cookie
    accept: '.xlsx', // 限制文件类型
    showUploadList: false, // 隐藏上传列表

    beforeUpload(file) {
      setLoading(true);
      readExcelFile(file, props);
      setLoading(false);
      return false; // 阻止自动上传
    },
    // openFileDialogOnClick: true,
    // onChange(info) {
    //   if (info.file.status !== 'uploading') {
    //     setLoading(false)
    //   }
    //   if (info.file.status === 'done') {
    //     message.success(`${info.file.name} 导入成功`);
    //   } else if (info.file.status === 'error') {
    //     message.error(`${info.file.name} 文件上传失败`);
    //   }
    // },
  }

  return (
    <>
      <Upload {...upProps}>
        <Button type='primary' icon={loading ? <SyncOutlined spin /> : <UploadOutlined />} disabled={loading} >导入</Button>
      </Upload >
    </>
  )
};

export default Import;